<?php

namespace app\admin\model\user;

use app\admin\model\User;
use app\common\model\MoneyLog;
use think\Exception;
use think\Model;


class Withdraw extends Model
{





    // 表名
    protected $name = 'user_withdraw';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [

    ];

    protected static function init()
    {
        self::beforeUpdate(function ($row) {

            $changedata = $row->getChangedData();
            if (isset($changedata['status']) && $changedata['status']==9) {
                $userInfo=User::get(['id'=>$row['uid']]);
//                $userInfo::update(['money'=>$userInfo['money']+$row['money']],['id'=>$row['uid']]);
                $userInfo->money=$userInfo['money']+$row['money'];
                $userInfo->save();
                MoneyLog::create(['user_id' => $row['uid'], 'money' => $row['money'], 'before' => $userInfo['money'], 'after' => $userInfo['money']+$row['money'],'type'=>1, 'memo' => '管理员变更金额']);
            }
        });


    }

    /**
     * 添加提现记录
     */
    public static function addWithdraw($user,$money,$accountId)
    {
        $info = \app\admin\model\user\Account::where('id',$accountId)->where('uid',$user->id)->where('status',1)->find();
        if(empty($info)){
            throw new Exception("账户信息获取失败");
        }
        $data = array(
            "uid"=>$user->id,
            "type"=>$info['type'],
            "accountId"=>$accountId,
            "username"=>$info['username'],
            "alipay"=>$info['type'] == 'alipay'?$info['alipay']:"",
            "bankname"=>$info['type'] == 'bank'?$info['bankname']:"",
            "bankbranch"=>$info['type'] == 'bank'?$info['bankbranch']:"",
            "bankno"=>$info['type'] == 'bank'?$info['bankno']:"",
            "money"=>$money,
            "price"=>$money,
            "status"=>1,
            "createtime"=>time(),
            "updatetime"=>time(),
        );
        $newId = self::insert($data,false,1);
        \app\common\model\User::money($user->id,-$money,3,"提现扣除","withdraw".date("Ymd",time()).$newId);
    }

    /**
     * 提现方式
     */
    public static function getTypesInfo()
    {
        return [
            'bank'=>'银行卡',
            'wechat'=>'微信',
        ];
    }
    /**
     * 状态信息
     * @return array
     */
    public static function getStatusInfo()
    {
        return [
            1=>'申请中',
            2=>'已审核',
            9=>'已拒绝',
        ];
    }






}
